package com.csj.cloud.order.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.csj.cloud.common.dao.OrderMapper;
import com.csj.cloud.common.entity.Member;
import com.csj.cloud.common.entity.Order;
import com.csj.cloud.common.vo.ResultBean;
import com.csj.cloud.core.service.user.MemberService;
import com.csj.cloud.core.service.order.OrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author chengshaojie123
 * @Description:
 * 负载均衡:loadbalance设置服务端的负载均衡策略（random：随机，roundrobin：轮询，leastactive：最少活跃数，consistentHash：一致性hash），当然该级别也可以全局配置
 * 集群容错模式:cluster(retry==重试次数，通常用户读取操作。
 *           "failfast"->只发起一次调用,失败立即报错.非幂等性的写操作，比如新增记录。
 *           "failsafe"->失败安全，出现异常时直接忽略；通常用于写入审计日志等操作。
 *           “Failback Cluster”->失败自动恢复，后台记录失败的请求，定时重发，通常用于消息通知操作,但是是不可靠的，重启丢失。
 *           "Forking "->并行调用多个服务器，只要一个成功即返回。通常用于实时性要求较高的读操作，但需要浪费更多服务资源。可通过forks="2"属性来设置最大并行数。)
 * @since 2019-11-19
 */
@Slf4j
@Service(loadbalance = "roundrobin",group = "one",timeout = 6000)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Reference
    private MemberService memberService;

    @Override
    @HystrixCommand(fallbackMethod = "TimeOutFallBack")
    public ResultBean addOrder(Order order1) {
        log.info("orderAdd发起调用{}",order1);
        ResultBean resultBean = new ResultBean();
        try {
            Thread.sleep(2000);
            //查询当前用户
            Member member = memberService.getCurrentMember();
            //下单时查询优惠信息-TODO
            Order order = new Order();
            order.setMemberId(member.getId());
            order.setReceiverName("name1");
            order.setReceiverPhone("17683009123");
            boolean b =  order != null ? this.insert(order) : false;
            if (b){
                resultBean.setData(order);
            }else {
                resultBean.setErrorMsg("下单失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return resultBean;


    }
    public ResultBean TimeOutFallBack(Order order1){
        ResultBean resultBean = new ResultBean();
        System.out.println("sorry, the request is timeout");
        return resultBean.setErrorMsg("TimeOutFallBack备选");
    }
}
